package com.ts.api.module.api.controller;

import com.gitee.apanlh.annotation.viewresolver.RequestParamVo;
import com.gitee.apanlh.util.base.Choose;
import com.gitee.apanlh.util.valid.RegexUtils;
import com.gitee.apanlh.util.valid.ValidParam;
import com.gitee.apanlh.web.model.vo.RequestVO;
import com.gitee.apanlh.web.model.vo.ResultVO;
import com.ts.api.module.api.service.ApiPlanRatingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 *  下游-星级回传
 *
 *  @author Pan
 */
@RestController
@RequestMapping("/plan/rating")
public class ApiPlanRatingController {

    @Autowired
    private ApiPlanRatingService apiPlanRatingService;

    /**
     *  接收下游-回传星级
     *
     *  @param  requestVO       请求对象
     *  @param  productId       主体id
     *  @param  productPlanId   主体计划id
     *  @return ResultVO
     */
    @PostMapping("/callback/{productId}/{productPlanId}")
    public ResultVO<Object> callback(@PathVariable Long productId, @PathVariable Long productPlanId, @RequestParamVo RequestVO requestVO) {
        String rating = requestVO.get("rating", String.class);
        String phoneMd5 = requestVO.get("phoneMd5", String.class);

        if (ValidParam.isEmpty(phoneMd5) || phoneMd5.length() != 32) {
            return ResultVO.fail("缺失md5");
        }
        if (ValidParam.isEmpty(rating) || !RegexUtils.isNumeric(rating)) {
            return ResultVO.fail("缺失星级评分");
        }
        if (!Choose.openClosed(0, 5, Integer.parseInt(rating))) {
            return ResultVO.fail("非法星级评分值");
        }

        //  记录星级回传
        try {
            apiPlanRatingService.ratingCallback(productId, productPlanId, phoneMd5, rating.toString());
        } catch (IllegalArgumentException illegalArgumentException) {
            return ResultVO.fail(illegalArgumentException.getMessage());
        } catch (Exception e) {
            return ResultVO.fail("回传异常");
        }
        return ResultVO.suc("回传成功");
    }
}
